window['UtilLin'] = {};

$(function () {
	$('[edit="ueditor"]').length&&$('[edit="ueditor"]').xheditor({tools:'mini',skin:'nostyle'});
})

//复选框
UtilLin.getCheck = (function () {
	return {
		isCheck:function (all,checks) {
			all.on("click",function () {
				if($(this).prop("checked") == true) {
					checks.filter(function () {
						return !$(this).prop("checked");
					}).attr("checked",true);
				}
				else {
					checks.filter(function () {
						return $(this).prop("checked");
					}).attr("checked",false);
				}
			});
			checks.on("click",function () {
				if(checks.filter(":checked").length == checks.length) {
					!all.prop("checked")&&all.prop("checked",true);
				}
				else all.prop("checked")&&all.prop("checked",false);
			})
		},
		diyCheck:function (all,checks,cls) {
			all.on("click",function () {
				if(!$(this).hasClass(cls)){
					$(this).addClass(cls);
					checks.filter(function () {
						return !$(this).hasClass(cls);
					}).addClass(cls);
				}
				else {
					$(this).removeClass(cls);
					checks.filter(function () {
						return $(this).hasClass(cls);
					}).removeClass(cls);
				}
			});
			checks.on("click",function () {
				$(this).toggleClass(cls);
				if(checks.filter("."+cls).length == checks.length) {
					!all.hasClass(cls)&&all.addClass(cls);
				}
				else all.hasClass(cls)&&all.removeClass(cls);
			})
		}
	}
})();


UtilLin.uiCommon = (function (){
	return {
		//模板类
		formatTpl:function (str,data) {
			return str.replace(/{(.*?)}/igm,function (strs,key) {
		        var keys = key.split(":"), str = data[keys[0]];
		        if(keys.length==1) {
		            return str ? str : "";
		        }
		        else {
		            var fns = keys[1].split("."), fn = window;
		            for(var i=0;i<fns.length;i++) {
		                fn = fn[fns[i]];
		            }
		            return fn(str);
		        }
		    })
		},
		//TAB内容切换
		boxTab:function (opt) {
			var e = opt.even || "click";
			opt.tab.on(e,function () {
				opt.box.hide();
				opt.box.eq($(this).index()).show();
				opt.callback&&opt.callback($(this));
			})
		},
		//验证
		Validate:function (self,obj) {
			var t = self.attr("vali"), n=self.attr("errormsg");
			if(obj) {
				t = obj.vali;
				n = obj.errormsg;
			}
			var vails = t.split("|"),errs = n.split("|"), _reg = top.window.Util.Validate._reg;
			for(var i=0;i<vails.length;i++) {
				var reg = new RegExp(_reg[vails[i]]);
				var blo = typeof _reg[vails[i]] == "function" ?  _reg[vails[i]](self.val()) : reg.test(self.val());
				if( self[0].tagName.toLowerCase() == "select" && Number(self.val()) == 0 ) {
						blo = false;
				}
                if( self[0].tagName.toLowerCase() == "textarea" && self.val().length == 0 ) {
						blo = false;
				}
				if(blo) {
					UtilLin.uiCommon.valiHide(self);
				} else{
					UtilLin.uiCommon.valiShow(self,errs[i]);
					return false;
				}
			}
			return true;
		},
		//tips提示
		Valitips:function (self,obj) {
			var t = self.attr("tips");
			if(obj) {
				t = obj.vali;
			}
			var vails = t.split("|");
			for(var i=0;i<vails.length;i++) {
				UtilLin.uiCommon.valiShow(self,vails[i],'tips');
				return false;
			}
			return true;
		},
		//错误提示显示
		valiShow:function (self,str,parm) {
			if(parm=='tips')
			{
				!self.nextAll("span.onShow,span.onCorrect,span.onError").length ? '' : self.nextAll("span.onShow,span.onCorrect,span.onError").hide();
				!self.nextAll("span.onShow").length ? self.nextAll("span.onShow").text(str) : self.nextAll("span.onShow").text(str).show();
			}
			else
			{
				!self.nextAll("span.onShow,span.onCorrect").length ? '' : self.nextAll("span.onShow,span.onCorrect").hide();
			    !self.nextAll("span.onError").length ? self.parent().append('<span class="onError">'+str+'</span>') : self.nextAll("span.onError").text(str).show();
				!self.hasClass("text-err")&&self.addClass("text-err");
			}
			
		},
		//错误提示隐藏
		valiHide:function (self) {
			self.hasClass("text-err")&&self.removeClass("text-err");
			!self.nextAll("span.onShow,span.onCorrect,span.onError").length ? '' : self.nextAll("span.onShow,span.onCorrect,span.onError").hide();
			!self.nextAll("span.onCorrect").length ? self.parent().append('<span class="onCorrect">输入正确</span>') : self.nextAll("span.onCorrect").text('输入正确').show();
		},
		//密码验证
		valipass:function (old,news,str) {
			if(old.val() != news.val()) {
				UtilLin.uiCommon.valiShow(old,str);
				UtilLin.uiCommon.valiShow(news,str);
				return false;
			}
			else {
				UtilLin.uiCommon.valiHide(old);
				UtilLin.uiCommon.valiHide(news);
				return true;
			}
		},
		//多验证
		Validates:function (form) {
			var t = true, self = this;
			form.find(":input[vali]").each(function () {
				if(!self.Validate($(this))) {
					t = false;
				}
			});
			return t;
		},
		//代替form 提交 提取内容
		inputObj:function (self) {
			var obj = {};
			self.find(":input").each(function () {
				var name = this.name, type = this.type;
				if(type=="hidden") type = "text";
				if(type=="file") {
					return;
				}
				switch(type) {
					case "radio":      //单选框
						if(this.checked == true) obj[name] = $(this).val();	
						break;
					case "checkbox":    //复选框数组
						if(!obj[name]) {
							obj[name] = [];
						}
						if(this.checked == true) obj[name].push($(this).val());
						break;
					case "text":
						if(!obj[name]) {	//单输入框
							obj[name] = $(this).val();
						}
						else if(obj[name] && !jQuery.isArray(obj[name])) {	//输入框数组
							var k = obj[name];
							obj[name] = [k];
						}
						jQuery.isArray(obj[name])&&obj[name].push($(this).val());
						break;
					default:    //其它
						obj[name] = $(this).val();
				}
			});
			return obj;
		},
		//lable隐藏
		lableHide:function (arr) {
			$("#"+arr.join(",#")).on("focus",function () {
				$("label[for='"+this.id+"']").hide();
			}).on("blur",function () {
				!$(this).val().length&&$("label[for='"+this.id+"']").show();
			})
		},
		//只限数字
		isNuber:function (self) {
			var reg = new RegExp("^[0-9]{1,20}$");
			if(!reg.test(self.val())) {
				self.val("0");
			}
		}
	}
})();

UtilLin.tips = function (str,type,time) {
	top.window.Core.MinMessage.Show({"text":str,"type":type,"timeout":time||1500});
	return false;
};
UtilLin.tipsHiden = function () {
	top.window.Core.MinMessage.Hide();
	return false;
}

UtilLin.Ajax = function (url,data,callback,err) {
	$.ajax({
		url: url,
		type: 'POST',
		dataType: 'json',
		data: data,
		success: function(json) {
			if(json.state) {
				callback&&callback(json);
			}
			else{
				if(!err) UtilLin.tips(json.msg || json.err_msg,"err");
				else callback&&callback(json);
			} 
		},
		error: function(xhr, textStatus, errorThrown) {
			UtilLin.tips("网络异常请刷新");
		}
	});
};

UtilLin.reload = function () {
	setTimeout(function () {
		 window.location.reload();
	},0)
}

function fileselchange(){
            var filePath = $(this).val();
            var fileArr = filePath.split('\\');
            var $self=$(this);
            if(fileArr.length < 0){
                fileArr = filePath.split('/');
            }
            var inputId=$self.attr("id");
            var inputName=$self.attr("name");
            var inputtype=$self.attr("img_type");
            var filetype=$self.attr("file_type");
            if(fileArr.length > 0){
                var fileName = fileArr[fileArr.length-1];
                var fileType = fileName.split('.');
                if(fileType.length > 0){
                    var tType = fileType[fileType.length-1].toLowerCase();
                    var typeflag = false;
                    filetype = filetype ? filetype : 'jpg,png,gif,jpeg';
                    var filetypes = filetype.split(',');console.info(filetype);
                    for(f in filetypes) {
                        if(tType == filetypes[f]) {
                            typeflag = true;
                            break;
                        }
                    }
                    if(typeflag){
                        $.ajaxFileUpload({
                            url:"?ct=index&ac=upload",
                            secureuri:false,
                            fileElementId:inputId,
                            dataType: 'json',
                            data:{upload:inputName,img_type:inputtype},
                            success: function (data, status)
                            {
                                $self.replaceWith($self[0].outerHTML);
                                $("#"+inputId).change(fileselchange);
                                if(data.state)
                                {
                                    
                                    if($("input[type='hidden'][rel='"+inputId+"']").length){
                                    	if($self.attr("imgarr") && $self.attr("imgarr") == "true") {
                                    		var t = $("div[rel='"+inputId+"']:eq(0)"), s= t.clone(true);
                                    		s.find("img").attr({"src":data.path});

                                    		if(s.find("input").length) {
                                    			s.find("input").remove();
                                    		}

                                    		s.append('<input type="hidden" name="'+inputName+'" rel="'+inputId+'" value="'+data.path+'" />');
                                    		$("div[rel='"+inputId+"']:last").after(s);

                                    	}else {
                                    		$("input[type='hidden'][rel='"+inputId+"']").val(data.path);

                                    		if($("div[rel='"+inputId+"']").length) {
                                    			$("div[rel='"+inputId+"']").show();
                                    		}
                                    		$("img[rel='"+inputId+"']").attr("src",data.path);
                                    	}

                                    	if($("div[rel='"+inputId+"']").length >=5) {
                                    		$(".form-line").hide();
                                    	}

                                    }
                                    else {
                                    	if(inputName =="product") {
                                    		inputName = inputName +"[]";
                                    	}
                                    	$("#"+inputId).after('<input type="hidden" name="'+inputName+'" rel="'+inputId+'" value="'+data.path+'" />');
                                    	$("[rel='"+inputId+"_img']").hide();
                                    	if($("div[rel='"+inputId+"']").length) {
                                    		$("div[rel='"+inputId+"']").show();
                                    	}
                                    	$("img[rel='"+inputId+"']").attr("src",data.path);

                                    	if($self.attr("imgarr") && $self.attr("imgarr") == "true") {
                                    		$("div[rel='"+inputId+"']").append('<a href="javascript:;" class="button btn-gray" red ="del_img">删除图片</a>');
                                    	}

                                    }
                                    
                                }
                                else
                                {
                                    alert(data.err_msg);
                                }
                            },
                            error: function (data, status, e)
                            {
                                $self.replaceWith($self[0].outerHTML);
                                $("#"+inputId).change(fileselchange);
                                alert(e)
                            }
                        });
                    }
                    else{
                        $(this).val("");
                        //$("txt").html("未选择文件");
                        alert("仅支持"+filetype);
                    }
                }
            }
}
/*传参数：img_type:图片类型;field:上传表单控件name
        img_type值有：
        face:头像
        product:产品
        logo:LOGO
        banner:banner
        slide:幻灯片
        news:新闻图片
        mark_ico:网站标志图片
*/
